package com.cnhis.drgs.core.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.util.Properties;

public class DataSourceUtil {
    public static DataSource getDruidDataSource(Properties p) {
        try {
            return DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDruidDataSource() {
        try {
            Properties p = new Properties();
            p.load(DataSourceUtil.class.getResourceAsStream("/jdbc.properties"));
            return getDruidDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDruidDataSource(String host, int port, String schema, String username, String password) {
        Properties properties = new Properties();
        //驱动类名
        properties.put("driverClassName", "com.mysql.jdbc.Driver");
        //数据库连接URL
        properties.put("url", String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false", host, port, schema));
        //数据库用户名
        properties.put("username", username);
        //数据库密码
        properties.put("password", password);
        return getDruidDataSource(properties);
    }

    public static DataSource getSqlServerDruidDataSource(String host, int port, String schema, String username, String password) {
        Properties properties = new Properties();
        //驱动类名
        properties.put("driverClassName", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
        //数据库连接URL
        properties.put("url", String.format("jdbc:sqlserver://%s:%s;DatabaseName=%s", host, port, schema));
        //数据库用户名
        properties.put("username", username);
        //数据库密码
        properties.put("password", password);
        return getDruidDataSource(properties);
    }
}
